import {
  MessageBody,
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
  WsResponse,
} from '@nestjs/websockets';
import { from, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Server } from 'socket.io';
import * as WebSocket from 'ws';
import { temp } from './ws-temp';

@WebSocketGateway(8080, {
  cors: {
    origin: '*',
  },
  transports: ['websocket'],
})
export class ScoketGateway {
  @WebSocketServer()
  server: Server;

  @SubscribeMessage('events')
  // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  onEvent(@MessageBody() data: any): Observable<WsResponse<number>> {
    return from([1, 2, 3]).pipe(
      map((item) => ({ event: 'events', data: item })),
    );
  }

  // @SubscribeMessage('message')
  // onCreateMessage(data) {
  //   temp.clientMap.get(0)?.send(
  //     JSON.stringify({
  //       event: 'checkin/create-message',
  //       data: data,
  //     }),
  //   );
  // }

  @SubscribeMessage('identity')
  async identity(@MessageBody() data: number): Promise<number> {
    console.log('接收identity的数据', data);
    // await new Promise((reslove,reject)=>{
    //   setTimeout(reslove,2000)
    // })
    return data;
  }

  PublicMessage(message: string): void {
    setInterval(() => {
      this.server.emit('exception', `我是服务端发来的消息${message}`);
    }, 1000);
  }
}
